﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;

using HisNet.Data;
using HisNet.Web.Cache;

namespace WebTest.Admin
{
    public class ZDManager
    {
        private static ZDManager instance = new ZDManager();



        private ZDManager()
        {
        }

        public static ZDManager Instance
        {
            get
            {
                return instance;
            }
        }

        /// <summary>
        /// 获取字典，并缓存
        /// </summary>
        /// <param name="dict"></param>
        /// <returns></returns>
        public DataTable GetDictData(string dict)
        {
            return CacheHelper.Instance.GetEntity<DataTable>(string.Format("{0}_{1}", Consts.CacheDict, dict),
                TimeSpan.FromMinutes(Consts.CacheMinute),()=>
            {
                using (DbSession dbSession = new DbSession(Consts.OAConnectionName))
                {
                    string sql = string.Format(@"SELECT * FROM {0} ", dict);
                    return dbSession.Query(sql);

                }
            });

        }

        public DataTable GetDictData(string dict,string bm)
        {
            DataTable dt = GetDictData(dict);
            if (dt != null)
            {
                DataRow[] dr = dt.Select(string.Format("BM='{0}'", bm));
                if (dr.Count() > 0)
                {
                    return dr.CopyToDataTable();
                }
                else
                {
                    return null;
                }                 
                
            }
            else
            {
                return null;
            }

        }


        public string GetDicMC(string dict,string bm)
        {
            DataTable dt = GetDictData(dict,bm);
            if (dt != null && dt.Rows.Count > 0)
            {
                return dt.Rows[0]["MC"].ToString();
            }
            else
            {
                return bm;
            }

        }

        /// <summary>
        /// 获取由SQL语句形成的字典表，并缓存
        /// </summary>
        /// <param name="dict"></param>
        /// <param name="sql"></param>
        /// <returns></returns>
        public DataTable GetSQLDictData(string dict,string sql)
        {
            return CacheHelper.Instance.GetEntity<DataTable>(string.Format("{0}_{1}", Consts.CacheSqlDict, dict),
                TimeSpan.FromMinutes(Consts.CacheMinute), () =>
                {
                    using (DbSession dbSession = new DbSession(Consts.OAConnectionName))
                    {
                        string sql1 = string.Format(@"SELECT * FROM ({0}) A ", sql);
                        return dbSession.Query(sql1);

                    }
                });

        }




    }
}